package com.mk.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mk.annotation.AuthCheck;
import com.mk.common.*;
import com.mk.contants.UserConstant;
import com.mk.exception.BusinessException;
import com.mk.exception.ErrorCode;
import com.mk.exception.ThrowUtils;
import com.mk.model.dto.space.SpaceAddRequest;
import com.mk.model.dto.space.SpaceEditRequest;
import com.mk.model.dto.space.SpaceQueryRequest;
import com.mk.model.dto.space.SpaceUpdateRequest;
import com.mk.model.entity.Space;
import com.mk.model.entity.User;
import com.mk.model.enums.SpaceLevelEnum;
import com.mk.model.vo.space.SpaceLevel;
import com.mk.model.vo.space.SpaceVO;
import com.mk.service.SpaceService;
import com.mk.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/space")
public class SpaceController {

    @Autowired
    private SpaceService spaceService;

    @Autowired
    private UserService userService;

    @Autowired
    private CacheUtils cacheUtils;


    @AuthCheck(UserConstant.DEFAULT_ROLE)
    @PostMapping("/add")
    public BaseResponse<Long> addSpace(@RequestBody SpaceAddRequest addRequest){
        // 参数校验，获取登录用户
        ThrowUtils.throwNotNull(addRequest);
        User loginUser = ThreadLocalUtil.get(UserConstant.USER_LOGIN_STATE);
        Long id = spaceService.addSpace(addRequest, loginUser);
        return ResultUtils.success(id);
    }

    /**
     * 删除空间
     * @param deleteRequest
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(UserConstant.DEFAULT_ROLE)
    public BaseResponse<Boolean> deleteSpaceById(@RequestBody DeleteRequest deleteRequest) {
        ThrowUtils.throwNotNull(deleteRequest);
        // 获取登录用户
        User loginUser = userService.getCurrentLoginUser();
        spaceService.deleteSpace(deleteRequest, loginUser);
        return ResultUtils.success(true);
    }

    /**
     * 更新空间（仅管理员可用）
     *
     * @return
     */
    @AuthCheck(UserConstant.ADMIN_ROLE)
    @PostMapping("/update")
     public BaseResponse<Long> updateSpace(@RequestBody SpaceUpdateRequest updateRequest) {
        ThrowUtils.throwNotNull(updateRequest);
        User loginUser = ThreadLocalUtil.get(UserConstant.USER_LOGIN_STATE);
        // 执行更新操作
        Long id = spaceService.updateSpace(updateRequest, loginUser);
        return ResultUtils.success(id);
    }

    /**
     * 根据id获取空间信息（仅管理员可用）
     *
     * @param id
     * @return
     */
    @AuthCheck(UserConstant.ADMIN_ROLE)
    @GetMapping("/get")
    public BaseResponse<Space> getSpaceById(Long id) {
        ThrowUtils.throwIf(id == null || id < 0, ErrorCode.PARAMS_ERROR);
        Space space = spaceService.getById(id);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(space);
    }

    /**
     * 根据id获取空间（VO封装类）
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<SpaceVO> getSpaceVoById(Long id) {
        SpaceVO spaceVO = spaceService.getSpaceVOById(id);
        return ResultUtils.success(spaceVO);
    }

    /**
     * 分页获取空间列表 （仅管理员可用） (admin)
     *
     * @return
     */
    @AuthCheck(UserConstant.ADMIN_ROLE)
    @PostMapping("/list/page")
    public BaseResponse<Page<Space>> listSpaceByPage(@RequestBody SpaceQueryRequest queryRequest) {
        ThrowUtils.throwNotNull(queryRequest);
        // 构造查询条件
        QueryWrapper<Space> queryWrapper = spaceService.getQueryWrapper(queryRequest);
        // 构造分页条件
        if (queryRequest.getCurrent() <= 0)
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "页码不能小于0");
        Page<Space> spacePage = new Page<>(queryRequest.getCurrent(), queryRequest.getPageSize());
        spaceService.page(spacePage, queryWrapper);
        return ResultUtils.success(spacePage);
    }

    /**
     * 分页获取空间列表 （封装类） （public, user, admin）
     *
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<SpaceVO>> listSpaceVOByPage(@RequestBody SpaceQueryRequest queryRequest) {
        Page<Space> spacePage = listSpaceByPage(queryRequest).getData();
        Page<SpaceVO> spaceVOPage = spaceService.getSpaceVOPage(spacePage);
        return ResultUtils.success(spaceVOPage);
    }

    /**
     * 编辑空间信息（用户可用） （user, admin）
     *
     * @return
     */
    @AuthCheck(UserConstant.DEFAULT_ROLE)
    @PostMapping("/edit")
    public BaseResponse<Boolean> editSpace(@RequestBody SpaceEditRequest editRequest) {
        ThrowUtils.throwNotNull(editRequest);
        User loginUser = ThreadLocalUtil.get(UserConstant.USER_LOGIN_STATE);
        spaceService.editSpace(editRequest, loginUser);
        return ResultUtils.success(true);
    }

    @GetMapping("/list/level")
    public BaseResponse<List<SpaceLevel>> listSpaceLevel() {
        List<SpaceLevel> spaceLevelList = Arrays.stream(SpaceLevelEnum.values()) // 获取所有枚举
                .map(spaceLevelEnum -> new SpaceLevel(
                        spaceLevelEnum.getValue(),
                        spaceLevelEnum.getText(),
                        spaceLevelEnum.getMaxCount(),
                        spaceLevelEnum.getMaxSize()))
                .collect(Collectors.toList());
        return ResultUtils.success(spaceLevelList);
    }


}
